package com.hgyc.mom.eam.job;

import com.hgyc.mom.common.enums.PeriodTypeEnum;
import com.hgyc.mom.common.util.CronExpressionUtils;
import com.hgyc.mom.eam.entity.EamCheckMaintainPlan;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 动态注册定时任务
 * @author fwj
 * @since 2025/8/15 15:57
 **/
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class QuartzPlanScheduler {

    @Autowired
    private Scheduler scheduler;

    /**
     * 批量调度计划
     */
    public void schedulePlans(List<EamCheckMaintainPlan> plans) throws SchedulerException {
        for (EamCheckMaintainPlan plan : plans) {
            schedulePlan(plan);
        }
    }

    /**
     * 注册或更新单个计划
     */
    public void schedulePlan(EamCheckMaintainPlan plan) throws SchedulerException {
        String jobKeyName = "checkMaintainPlanJob_" + plan.getId();
        String triggerKeyName = "checkMaintainPlanTrigger_" + plan.getId();

        // 如果任务已存在，则先删除（避免重复）
        JobKey jobKey = JobKey.jobKey(jobKeyName);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }

        // 枚举转换
        PeriodTypeEnum periodType = PeriodTypeEnum.of(plan.getPlanType());
        int cycleType = plan.getCycleType() != null ? plan.getCycleType() : 1;

        // 生成 Cron（固定 0 点执行）
        String cron = CronExpressionUtils.generate(
                periodType,
                cycleType,
                0,  // hour
                0,  // minute
                null, // weekDay（可从 plan 中取）
                null  // dayOfMonth（可从 plan 中取）
        );

        JobDetail jobDetail = JobBuilder.newJob(CheckMaintainPlanJob.class)
                .withIdentity(jobKeyName)
                .usingJobData("planId", plan.getId())
                .build();

        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity(triggerKeyName)
                .withSchedule(CronScheduleBuilder.cronSchedule(cron))
                .build();

        scheduler.scheduleJob(jobDetail, trigger);
    }

    /**
     * 取消任务
     */
    public void cancelPlan(Long planId) throws SchedulerException {
        JobKey jobKey = JobKey.jobKey("checkMaintainPlanJob_" + planId);
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
    }

    /**
     * 更新任务
     */
    public void updatePlan(EamCheckMaintainPlan plan) throws SchedulerException {
        schedulePlan(plan); // 直接走注册逻辑，会自动覆盖
    }
}

